<template>
  <div>
    <!-- 地址 -->
<view class="address">
  <view class="btn" v-if="!address.userName">
    <button type="primary" plain @click="handleChooseAddress">添加收货地址</button>
  </view>
  <view class="address_detail" v-else>
    <view class="user_info">
      <view class="user_name">收货人:{{address.username}}</view>
      <view class="user_address">{{address.all}}</view>
    </view>
    <view class="user_phone">{{address.telNumber}}</view>
  </view>
</view>
<!-- 购物车 -->
<view class="cart_content">
  <!-- 文字 -->
  <view class="cart_title">购物车</view>
  <!-- 主体 -->
  <view class="cart_main">
    <block v-if="cart.length!== 0">
      <!-- 每项 -->
      <view class="cart_item" v-for="(item,index) in cart" :key="index" :goods_id="item.goods_id">
        <!-- 复选框 -->
        <view class="checkbox_wrap">
          <checkbox-group @change="handleItemChange" :goods_id="item.goods_id">
            <checkbox :checked="item.check"></checkbox>
          </checkbox-group>
        </view>
        <!-- 图片 -->
        <navigator class="cart_pic" url="">
          <image mode="widthFix" :src="item.goods_small_logo"></image>
        </navigator>
        <!-- 商品信息 -->
        <view class="cart_info">
          <view class="goods_name">{{item.goods_name}}</view>
          <view class="goods_price_wrap">
            <view class="goods_price">${{item.goods_price}}</view>
            <view class="goods_tool">
              <!-- 减号 -->
              <view class="btn" @click="editNum(-1,item.goods_id)">
                -
              </view>
              <view class="goods_num">{{item.num}}</view>
              <!-- 加号 -->
              <view class="btn" @click="editNum(1,item.goods_id)">
                +
              </view>
            </view>
          </view>
        </view>
      </view>
    </block>
    <!-- 购物车空 --显示 -->
    <block v-else>
      <image src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582298919125&di=0b3e6d7e9c216243f3724f7ef59b5271&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fe1b1467beea0a9c7d6a56b32bac6d7e5dcd914f7c3e6-YTwUd6_fw658" mode="wigthFix" />
    </block>
  </view>
</view>
<!-- 底部 -->
<view class="footer_tool">
  <!-- 全选 -->
  <view class="chexk_all_wrap">
    <checkbox-group @change="handleALlCheck">
      <checkbox :checked="allCheck">全选</checkbox>
    </checkbox-group>
  </view>
  <!-- 总价格 -->
  <view class="total_price_wrap">
    <view class="total_price">
      合计:
      <text class="price_text">{{totalPrice}}</text>
    </view>
    <view class="yunfei">包含运费</view>
  </view>
  <!-- 结算 -->
  <view class="total_pay_wrap" @click="handleToPay">
    <text>结算({{totalNum}})</text>
  </view>
</view>
  </div>
</template>

<script>
import { getSetting, chooseAddress, openSetting, showModal, showToast } from '../../utils/tools';
export default {
  data() {
    return {
      address: {}, // 购物地址
      cart: [],//购物车列表
      allCheck: false,//是否全选
      totalPrice: 0,//总价
      totalNum: 0//总件数
    }
  },
  methods:{
    // 点击结算
    async handleToPay() {
      if (!this.address.userName) {
        await showToast({ title: '请添加地址' })
        return
      }
      if (this.totalNum === 0) {
        await showToast({ title: '请选择商品' })
        return
      }
      wx.navigateTo({
        url: '/pages/pay/main',
        success: (result) => {},
        fail: () => { },
        complete: () => { }
      });
    },
    // 勾选改变
    handleItemChange(e) {
      const goods_id = e.currentTarget.dataset.id
      // console.log(goods_id);
      let { cart } = this.data
      let index = cart.findIndex(v => v.goods_id === goods_id)
      cart[index].check = !cart[index].check    // 取反
      wx.setStorageSync("cart", cart)
      // 调用
      this.setCart(cart)
    },
    // 获取地址
    async handleChooseAddress() {
      console.log('收货地址');
      try {
        // 获取权限状态
        const res1 = await getSetting()
        console.log(res1);
        const scopeAddress = res1.authSetting["scope.address"];
        //  如果用户曾经获取权限时点过取消,让他打开设置设置
        if (scopeAddress === false) {
          // 打开设置
          await openSetting()
        }
        // 如果用授予权限时点过确定或者从来没点过,
        let address = await chooseAddress()
        address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;
        console.log(address);
        wx.setStorageSync("address", address)
        this.setData({
          address
        })
      } catch (err) {
        console.error(err)
      }
    },
    // 增减
    async editNum(operation,id) {
      console.log(operation,id);
      const index = this.cart.findIndex(v => v.goods_id == id)
      console.log('当前点击的index',index)
      if (this.cart[index].num === 1 && operation === -1) {
        const result = await showModal({ content: '确定删除?' })
        if (result.confirm) {
          console.log('拜你个拜')
          this.cart.splice(index, 1)
          this.setCart(this.cart)
        } else if (result.cancel) {
          console.log('那没事了')
        }
      } else {
        this.cart[index].num += operation
        this.setCart(this.cart)
      }
    },
    // 点击全选
    handleALlCheck() {
      // 取反
      this.allCheck = !this.allCheck
      this.cart.forEach(v => v.check = this.allCheck)
      // console.log(cart);
      // 调用
      this.setCart(this.cart)
    },
    // 设置购物车状态: 总数 总价 勾选
    setCart(cart) {
      // 选中,总价,总数
      let allCheck = true, totalPrice = 0, totalNum = 0
      //cart是遍历的数据数组,cart.check有值,true或者false
      //every返回布尔值,空数组.every返回true
      // const allCheck = cart.length === 0 ? false : cart.every(v => v.check)
      // 遍历
      cart.forEach(v => {
        if (v.check) {
          totalPrice += v.num * v.goods_price
          totalNum += v.num
        } else {
          allCheck = false
        }
      })
      // 优化bug
      allCheck = cart.length != 0 ? allCheck : false;
      wx.setStorageSync("cart", cart)
      // 更新数据
      this.cart=cart
      this.allCheck=allCheck
      this.totalPrice=totalPrice
      this.totalNum=totalNum 
    }
  },
  // 监听页面显示
  onShow: function () {
    // 获取地址
   this.address = wx.getStorageSync('address')
    // 更新购物车
    let cart = wx.getStorageSync('cart') || []
    // 调用
    this.setCart(cart)
  },
}
</script>

<style lang='less' scope>
.address {

  padding: 20rpx;

  // 按钮--添加地址
  button {
    width: 60%;
  }

  .address_detail {
    width: 100%;
    display: flex;
    font-size: 28rpx;

    .user_info {
      flex: 5;
    }

    .user_phone {
      flex: 3;
      text-align: center;
    }
  }

}

// 购物车区域
.cart_content {
  .cart_title {
    padding: 20rpx;
    font-size: 36rpx;
    color: var(--themeColor);
    border-top: 1rpx solid currentColor;
    border-bottom: 1rpx solid currentColor;
  }

  .cart_main {
    width: 100%;

    .cart_item {
      padding: 10px;
      display: flex;
      border-bottom: 1px solid #ccc;

      .checkbox_wrap {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }

      .cart_pic {
        flex: 2;
        display: flex;
        flex-direction: column;
        justify-content: center;

        image {
          width: 80%;
        }
      }

      .cart_info {
        flex: 4;
        display: flex;
        // 上下排
        flex-direction: column;
        justify-content: space-around;
        align-items: center;

        // 上 - 名字
        .goods_name {
          display: -webkit-box;
          overflow: hidden;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          color: #666;
        }

        // 下 - 价格
        .goods_price_wrap {
          width: 100%;
          display: flex;
          justify-content: space-between;

          // 价格数字
          .goods_price {
            color: var(--themeColor);
            font-size: 34rpx;
          }

          // 增减按钮
          .goods_tool {
            display: flex;
            justify-content: center;
            align-items: center;

            .btn {
              width: 55rpx;
              height: 55rpx;
              display: flex;
              justify-content: center;
              align-items: center;
              border: 1rpx solid #ccc;
            }

            .goods_num {
              width: 55rpx;
              height: 55rpx;
              display: flex;
              justify-content: center;
              align-items: center;
            }
          }
        }
      }

    }
  }
}

// 底部
.footer_tool {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 90rpx;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;

  // 左
  .chexk_all_wrap {
    flex: 2;
    display: flex;
    justify-content: center;
    align-items: center;

  }

  // 中
  .total_price_wrap {
    flex: 4;
    text-align: right;
    padding-right: 15rpx;


    .total_price {
      .price_text {
        color: var(--themeColor);
        font-size: 34rpx;
        font-weight: 600;
      }
    }

    .yunfei {}
  }

  // 右
  .total_pay_wrap {
    flex: 3;
    background-color: var(--themeColor);
    height: 100%;
    color: #fff;
    font-size: 32rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>